package com.qezhhnjy.demo.ftp.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.qezhhnjy.demo.ftp.config.FtpConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.Objects;

/**
 * @author zhaoyangfu - 2021/2/25 14:32
 */
@Component
@Slf4j
public class FtpUtil {

    @Resource
    private FtpConfig ftpConfig;

    public FTPClient client() {
        return Objects.requireNonNull(ftpConfig.ftpClient(), "FTP客户端连接失败");
    }

    /**
     * 将文件上传到 /项目根目录/年/月/日/文件后缀 目录下
     */
    public boolean upload(InputStream input, String fileName) {
        Objects.requireNonNull(input, "文件流不能为空");

        boolean returnValue = false;
        // 上传文件
        FTPClient client = client();
        try {

            StringBuilder sb = new StringBuilder(ftpConfig.getRootPath());
            LocalDate now = LocalDate.now();

            sb.append("/").append(now.getYear())
                    .append("/").append(now.getMonthValue())
                    .append("/").append(now.getDayOfMonth())
                    .append("/").append(FileUtil.getSuffix(fileName));


            if (!client.changeWorkingDirectory(sb.toString())) {
                for (String relative : StrUtil.split(sb.toString(), '/', true, true)) {
                    if (!client.changeWorkingDirectory(relative)) {
                        client.makeDirectory(relative);
                        client.changeWorkingDirectory(relative);
                    }
                }
            }
            // 上传文件到ftp
            returnValue = client.storeFile(fileName, input);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                input.close();
                client.logout();
                client.disconnect();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return returnValue;
    }
}
